#### Measuring support for liberal democracy
#### Code for revised draft of paper
#### Version 5 - February 2023

# libraries
library(tidyverse)
library(psych)
library(lavaan)
library(car)
library(semTable)
library(psychTools)
library(tth)
library(haven)
library(RColorBrewer)
library(matrixStats)

# read csv file
sd_dat = read.csv("brazil 2022.csv")

# examine responses
names(sd_dat)
summary(sd_dat)
sapply(sd_dat, table, useNA="ifany") # check if DKs and NAs are included and how they are coded

# filters variables of interest only
sd17 = sd_dat %>% select(frexp1, frexp2, frassc1, frassc2, frassc3, unisuff1,
                         unisuff2, decelec1, decelec2, frelect1, frelect2,
                         judcnstr1, judcnstr2, legcnstr1, legcnstr2, eqlaw1, eqlaw2)

# variable names if recoding is required 
names(sd17) = c("FREXP1", "FREXP2", "FRASSC1", "FRASSC2", "FRASSC3", "UNISUFF1", 
                "UNISUFF2", "DECELEC1", "DECELEC2", "FRELECT1", "FRELECT2", 
                "JUDCNSTR1", "JUDCNSTR2", "LEGCNSTR1", "LEGCNSTR2", 
                "EQLAW1", "EQLAW2")

## Plot item distributions

# colour palettes 
lik5 = c(brewer.pal(5, "BrBG"))
lik5_labs = c("StrAg", "SomeAg", "Neither", "SomeDis",
              "StrDis")

# plot
pdf("supdem_distr_brazil.pdf", height=8, width=6)
par(mfrow=c(5, 4), mar=c(3, 2, 0.5, 0.5), tcl=-0.2, cex=0.9, las=2, mgp=c(1.8, 0.9, 0))
for(i in 1:length(sd17)) {
  barplot(height = table(sd17[,i]) / dim(sd17)[1] * 100, names.arg=lik5_labs, 
          axes=FALSE, col=lik5, cex.names=0.7, mgp=c(1, 0.2, 0), ylim=c(0, 80))
  axis(side=2, labels=TRUE, cex.axis=0.7, mgp=c(1, 0.4, 0))
  text(x=1.5, y=75, names(sd17)[i], cex=0.8, adj=0)
}
dev.off()


## Recode to orient all items in a pro-democratic direction and DKs as "neither"; 
## change 99 to whatever code is used for DKs; if none, delete "99=3"
## This assumes the response set runs from 1=strongly agree to 5=strongly disagree;
sd_dat_r = sd17
dem_vnam = c("FREXP1", "FRASSC2", "UNISUFF2", "DECELEC2", "FRELECT1", "JUDCNSTR1", "LEGCNSTR2", "EQLAW2")
aut_vnam = c("FREXP2", "FRASSC1", "FRASSC3", "UNISUFF1", "DECELEC1", "FRELECT2", "JUDCNSTR2", "LEGCNSTR1", "EQLAW1")
sd_dat_r[, dem_vnam] = lapply(sd_dat_r[, dem_vnam], car::Recode, "1=5; 2=4; 3=3; 4=2; 5=1; 99=3; else=NA")
sd_dat_r[, aut_vnam] = lapply(sd_dat_r[, aut_vnam], car::Recode, "1=1; 2=2; 3=3; 4=4; 5=5; 99=3; else=NA")
sd_dat[, dem_vnam] = sd_dat_r[, dem_vnam]
sd_dat[, aut_vnam] = sd_dat_r[, aut_vnam]


## Reliability and dimensionality

# alpha
sd_cor = cor(sd_dat_r, use="pair")
psych::alpha(sd_cor)
alph_out <- psych::alpha(sd_cor)
write.csv(alph_out[[1]], file="sd_alpha.csv")

# eigenvalues of principal components
eigen(sd_cor)$values
write.csv(eigen(sd_cor)$values, file="sd_eigen.csv")

# 1-factor EFA
psych::fa(sd_dat_r, nfactors=1)
efa1 = psych::fa(sd_dat_r, nfactors=1)
efa_html = tth(fa2latex(efa1))
writeLines(efa_html, "sd_efa1.html")

# ordinal
sd_pcor = polychoric(sd_dat_r)$rho
write.csv(sd_pcor, "sd_pcormat.csv", row.names=TRUE)
psych::fa(sd_pcor, nfactors=1, n.obs=dim(sd_dat)[1])
efa_ord = psych::fa(sd_pcor, nfactors=1, n.obs=dim(sd_dat)[1])
efa_ord_html = tth(fa2latex(efa_ord))
writeLines(efa_ord_html, "sd_efa1_ord.html")


## CFA models

# appends wt object to the dataset
sd_dat_r$wt <- sd_dat$wt

# liberal democracy factor with orthogonal methods factor

cfa_mod_1 = '
SupLD =~ FREXP1 + FREXP2 + FRASSC1 + FRASSC2 + FRASSC3 + UNISUFF1 + UNISUFF2 
          + DECELEC1 + DECELEC2 + FRELECT1 + FRELECT2 + JUDCNSTR1 + JUDCNSTR2 
          + LEGCNSTR1 + LEGCNSTR2 + EQLAW1 + EQLAW2
PosVal =~ FREXP1 + FRASSC2 + UNISUFF2 + DECELEC2 + FRELECT1 + JUDCNSTR1 + LEGCNSTR2 + EQLAW2
'
# fit weighted model, note that the weight variable should be named here instead of "weight_var"

sd_cfa_1_std = cfa(cfa_mod_1, data=sd_dat_r, estimator="MLR", orthogonal=TRUE, 
                   std.lv=TRUE, sampling.weights = "wt")
semTable(sd_cfa_1_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_1fac_std_table_w.html")
sd_cfa_1_std_fit = fitMeasures(sd_cfa_1_std, output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_1_std_fit, file = "cfa_1fac_std_fit_w.csv", row.names = TRUE)

# liberal democracy factor with orthogonal methods factor, ordinal
sd_cfa_1_std = cfa(cfa_mod_1, data=sd_dat_r, estimator="WLSMV", orthogonal=TRUE, ordered=TRUE, 
                   std.lv=TRUE)
summary(sd_cfa_1_std, fit.measures=TRUE)
semTable(sd_cfa_1_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"), 
         type="html", file="cfa_1fac_ord_std_table.html")
sd_cfa_1_std_fit = fitMeasures(sd_cfa_1_std,  output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_1_std_fit, file = "cfa_1fac_std_ord_fit.csv", row.names = TRUE)

# electoral democracy and rule of laws factors with orthogonal methods factor

cfa_mod_2 = '
SupED =~ FREXP1 + FREXP2 + FRASSC1 + FRASSC2 + FRASSC3 + UNISUFF1 + UNISUFF2 
          + DECELEC1 + DECELEC2 + FRELECT1 + FRELECT2
SupRL =~  JUDCNSTR1 + JUDCNSTR2 + LEGCNSTR1 + LEGCNSTR2 + EQLAW1 + EQLAW2
PosVal =~ FREXP1 + FRASSC2 + UNISUFF2 + DECELEC2 + FRELECT1 + JUDCNSTR1 + LEGCNSTR2 + EQLAW2
PosVal ~~ 0*SupED
PosVal ~~ 0*SupRL
'
# include weights variable
sd_cfa_2_std = cfa(cfa_mod_2, data=sd_dat_r, estimator="MLR", std.lv=TRUE, 
                   sampling.weights="wt")
semTable(sd_cfa_2_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_2fac_std_table_w.html")
sd_cfa_2_std_fit = fitMeasures(sd_cfa_2_std, output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_2_std_fit, file = "cfa_2fac_std_fit_w.csv", row.names = TRUE)

# electoral democracy and rule of laws factors with orthogonal methods factor
sd_cfa_2_std = cfa(cfa_mod_2, data=sd_dat_r, estimator="WLSMV", ordered=TRUE, std.lv=TRUE)
summary(sd_cfa_2_std, fit.measures=TRUE)
semTable(sd_cfa_2_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"), 
         type="html", file="cfa_2fac_ord_std_table.html")
sd_cfa_2_std_fit = fitMeasures(sd_cfa_2_std, output = "matrix",
                               fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_2_std_fit, file = "cfa_2fac_std_ord_fit.csv", row.names = TRUE)

# lr test - 1 v 2-fac models

lavTestLRT(sd_cfa_1_std, sd_cfa_2_std, method = "satorra.bentler.2010")
write.csv(lavTestLRT(sd_cfa_2_std, sd_cfa_1_std, method = "satorra.bentler.2010"), 
          file = "lrtest_cfas.csv", row.names = TRUE)


## Trimmed 7-item scale

sd_dat_7 = sd_dat_r[, c("FREXP2", "FRASSC1", "UNISUFF1", "FRELECT2", "JUDCNSTR2", "LEGCNSTR1", "EQLAW1")]

# 1-factor CFA

cfa_mod_7i = 'SupLD =~ FREXP2 + FRASSC1 + UNISUFF1 + FRELECT2 + JUDCNSTR2 + LEGCNSTR1 + EQLAW1'

# include weights variable
sd_cfa_7i_std = cfa(cfa_mod_7i, data=sd_dat_r, estimator="MLR", std.lv=TRUE, 
                    sampling.weights="wt")
summary(sd_cfa_7i_std, fit.measures=TRUE)
semTable(sd_cfa_7i_std, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_7it_std_table_w.html")
sd_cfa_7i_fit = fitMeasures(sd_cfa_7i_std, output = "matrix",
                            fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_7i_fit, file = "cfa_7it_std_fit_w.csv", row.names = TRUE)

# 1-factor CFA, ordinal
sd_cfa_7i_ord = cfa(cfa_mod_7i, data=sd_dat_r, estimator="WLSMV", ordered=TRUE, std.lv=TRUE)
summary(sd_cfa_7i_ord, fit.measures=TRUE)
semTable(sd_cfa_7i_ord, paramSets = c("fits", "loadings", "latentvariances", "latentcovariances"),
         fits=c("chisq", "cfi", "rmsea", "srmr"), columns=c("est", "se", "p"),
         type="html", file="cfa_7it_ord_std_table.html")
sd_cfa_7i_fit = fitMeasures(sd_cfa_7i_ord, output = "matrix",
                            fit.measures = c("cfi", "cfi.robust", "rmsea", "rmsea.robust", "srmr"))
write.csv(sd_cfa_7i_fit, file = "cfa_7it_ord_std_fit.csv", row.names = TRUE)

# eigenvalues of 7-item scale
sd7_cor = cor(sd_dat_7, use="pair")
eigen(sd7_cor)$values
write.csv(eigen(sd7_cor)$values, file="sd7_eigen.csv")

# reliability of 7-item scale
psych::alpha(sd7_cor)
alph7_out <- psych::alpha(sd7_cor)
write.csv(alph7_out[[1]], file="sd7_alpha.csv")
# ordinal reliability
sd7_pcor = polychoric(sd_dat_7)$rho
alph7_ord_out <- psych::alpha(sd7_pcor)
write.csv(alph7_ord_out[[1]], file="sd7_ord_alpha.csv")

# create additive 7-item scale
sd_dat$SUPDEM_7IT = rowMeans(sd_dat_7)


## Correlations with criterion variables

# Use whichever of these variables you have in your survey
# and include others you think appropriate

# 1. Linz democratic support (3 statements) - LINZ_SUPDEM: recode such that support democ = 3 and support auth = 1. 
# 2. Churchill democratic support "Democracy may have problems" - CHURCH_SUPDEM: recode such that support is high, oppose is low
# 3. Strong leader item - STRONG_LEAD: recode such that support is high, oppose is low
# 4. Importance of democracy item - IMPORT_DEMOC: recode such that support is high, oppose is low
# 5. Satisfaction with democracy - SATIS_DEM: recode such that satisfaction is high
# 6. Government/executive approva - GOVT_APPROV (or similar): recode such that approval is high
# 7. Left-right / lib-cons ideology - LR_IDEOL or LC_IDEOL: recode such that right / conservative is high
# 8. Populist attitudes scale - POP_ATT: recode each item such that populism is high and then create scale such that populism is high
# 9. Political trust scale - POL_TRUST: recode each item such that trust is high and then create scale such that trust is high

# imports dataset with criterion variables
crit.vars <- read.csv('brazil 2022.csv')

# selects criterion variables only
crit.vars <- crit.vars %>%
  select(ing4 : m1)

head(crit.vars)

# recodes dem2
table(crit.vars$dem2)

# those who prefer democracy over any other kind of government are categorized
# as 1
crit.vars$dem2 <- ifelse(crit.vars$dem2 == 2, 3,
                         ifelse(crit.vars$dem2 == 3, 1, 
                                ifelse(crit.vars$dem2 == 1, 2, NA)))

# recodes support for strong leaders
crit.vars$wvs1 <- max(crit.vars$wvs1, na.rm = T) - crit.vars$wvs1

# creates populism additive scale
crit.vars$populism <- rowMeans(crit.vars[, c('pop1', 
                                             'pop2', 
                                             'pop3', 
                                             'pop4', 
                                             'pop5', 
                                             'pop6')], na.rm = TRUE)

# reverses executive approval
table(crit.vars$m1)

crit.vars$m1 <- max(crit.vars$m1, na.rm = T) - crit.vars$m1

# selects relevant variables and assign an order to them
sd_dat2.crit <- bind_cols(sd_dat %>% select(SUPDEM_7IT),
                          crit.vars %>% select(dem2,
                                               ing4,
                                               wvs1,
                                               wvs5,
                                               pn4,
                                               m1,
                                               l1,
                                               populism))

# renames variables
names(sd_dat2.crit) = c("SUPDEM_7IT", "LINZ_SUPDEM", "CHURCH_SUPDEM", 
                        "STRONG_LEAD", "IMPORT_DEMOC", "SATIS_DEM", 
                        "GOVT_APPROV", "LR_IDEOL", "POP_ATT")

# create and save mixed correlation matrix
cor_items = c("SUPDEM_7IT", "LINZ_SUPDEM", "CHURCH_SUPDEM", "STRONG_LEAD", "IMPORT_DEMOC", 
              "SATIS_DEM", "GOVT_APPROV", "LR_IDEOL", "POP_ATT")

crit_cor = mixedCor(sd_dat2.crit[, cor_items])$rho
write.csv(crit_cor, file="sd7_crit_cormat.csv")
